<template>
	<view>
		<!-- 选择支付方式弹窗 -->
		<uni-popup ref="choosePaymentPopup" type="center">
			<view class="choose-payment-popup popup" @touchmove.prevent.stop>
				<view class="popup-header">
					<text class="tit">支付方式</text>
					<text class="iconfont iconclose" @click="close()"></text>
				</view>
				<scroll-view scroll-y="true" class="popup-body" :class="{ 'safe-area': isIphoneX }">
					<view class="pay-money">
						<!-- <text class="unit">{{ $lang('common.currencySymbol') }}</text> -->
						<text class="money">支付金额{{ payMoney | moneyFormat }}元</text>
					</view>

					<view class="payment-item" v-if="balanceDeduct > 0">
						<view class="iconfont iconyue"></view>
						<view class="info-wrap">
							<text class="name">消费券抵扣</text>
							<view class="money">
								<text
									v-if="orderData.day_user_coupon_status && orderData.day_user_coupon_max > 0 && balanceDeduct > orderData.day_user_coupon_max && isBalance == 1">
									剩余¥{{ balanceDeduct }}，今日剩余用券金额最高为¥{{ orderData.day_user_coupon_max }}
								</text>
								<text v-else>
									可用¥{{ balanceDeduct }}
								</text>
							</view>
						</view>
						<ns-switch class="balance-switch" @change="useBalance" :checked="isBalance == 1"></ns-switch>
					</view>
					<block v-if="payMoney > 0">
						<block v-if="payTypeList.length">
							<view class="payment-item" v-for="(item, index) in payTypeList" :key="index"
								@click="payIndex = index">
								<block v-if="item.type != 'wechatpay' && item.type != 'alipay'">
									<image class="icon_img" :src="$util.img('public/uniapp/'+item.icon+'.png')"
										mode="aspectFit"></image>
									<view class="info-wrap">
										<text class="name">{{ item.name }}</text>
									</view>
								</block>
								<block v-else>
									<view class="iconfont" :class="item.icon"></view>
									<text class="name">{{ item.name }}</text>
								</block>
								<text class="iconfont"
									:class="payIndex == index ? 'iconyuan_checked color-base-text' : 'iconcheckboxblank'"></text>
							</view>
						</block>
						<block v-else>
							<view class="empty">平台尚未配置支付方式！</view>
						</block>
					</block>
				</scroll-view>
				<view class="popup-footer" :class="{ 'bottom-safe-area': isIphoneX }">
					<view class="confirm-btn color-base-bg" @click="confirm()">确认支付</view>
				</view>
			</view>
		</uni-popup>
		<pwd-popup ref="pwdPopup" @complete="complete"></pwd-popup>
		<!-- 转账信息 -->
		<ns-transfer-info ref="transFerInfo"></ns-transfer-info>
	</view>
</template>

<script>
	import nsTransferInfo from '@/components/ns-transfer-info/ns-transfer-info.vue';
	import uniPopup from '@/components/uni-popup/uni-popup.vue';
	import nsSwitch from '@/components/ns-switch/ns-switch.vue';
	import pwdPopup from '@/components/passwordp-opup/pwd-popup/pwd-popup.vue';

	// #ifdef H5
	import {
		Weixin
	} from 'common/js/wx-jssdk.js';
	// #endif

	export default {
		name: 'payment',
		components: {
			uniPopup,
			nsSwitch,
			pwdPopup,
			nsTransferInfo
		},
		props: {
			balanceDeduct: {
				type: [Number, String],
				default: ''
			},
			isBalance: {
				type: Number,
				default: 0
			},
			payMoney: {
				type: [Number, String],
				default: 0
			},
			payData: {
				type: Object,
				default: {}
			},
			orderData: {
				type: Object,
				default: {}
			}
		},
		data() {
			return {
				isIphoneX: false,
				payIndex: 0,
				// #ifdef H5 || APP || APP-PLUS
				payTypeList: [{
						name: '支付宝支付',
						icon: 'iconzhifubaozhifu-',
						type: 'alipay'
					},
					{
						name: '微信支付',
						icon: 'iconweixin1',
						type: 'wechatpay'
					},
					{
						name: '转账支付',
						icon: 'iconbankcard',
						type: 'YeePayBank'
					}
				],
				timer: null,
				// #endif
				// #ifdef MP-WEIXIN
				payTypeList: [{
						name: '微信支付',
						provider: 'wxpay',
						icon: 'iconweixin1',
						type: 'wechatpay'
					},
					{
						name: '转账支付',
						icon: 'iconbankcard',
						type: 'YeePayBank'
					}
				],
				isMatched: 0, // 支付是否需要校验
				// #endif
				payInfo: {}
			};
		},
		created() {
			this.isIphoneX = this.$util.uniappIsIPhoneX();
			this.getPayType();
			// #ifdef MP-WEIXIN
			if (uni.getStorageSync('paySource') == '') this.payIsMatched();
			// #endif
		},
		methods: {
			// #ifdef MP-WEIXIN
			payIsMatched() {
				let options = wx.getLaunchOptionsSync();
				this.$api.sendRequest({
					url: '/shopcomponent/api/weapp/scenecheck',
					data: {
						scene: options.scene
					},
					success: res => {
						if (res.code == 0) this.isMatched = res.data;
					}
				})
			},
			// #endif
			open() {
				this.$refs.choosePaymentPopup.open();
			},
			close() {
				this.$refs.choosePaymentPopup.close();
			},
			// 使用消费券
			useBalance() {
				if (this.isBalance == 0){
					if (this.orderData.day_user_coupon_status == false) {
						this.$util.showToast({
							title: '今日用券金额已达上限！'
						});
						return;
					} else {
						if (this.orderData.shop_online_limit == 1){
							this.$util.showToast({
								title: '今日商家收款已达上限'
							});
							return;
						}
						if(parseFloat(this.orderData.day_user_coupon_max) > 0 && parseFloat(this.balanceDeduct) > parseFloat(this.orderData.day_user_coupon_max)){
							const tipString = '今日剩余用券金额最高为' + this.orderData.day_user_coupon_max + '元';
							this.$util.showToast({
								title: tipString
							});
						}
						this.$emit('useBalance');
					}
				}else{
					this.$emit('useBalance');
				}
			},
			confirm() {
				if (this.payTypeList.length == 0 && this.payMoney > 0) {
					this.$util.showToast({
						title: '请选择支付方式！'
					});
					return;
				}
				this.$refs.choosePaymentPopup.close();
				if (this.isBalance) { //消费券支付
					this.$refs.pwdPopup.show();
				} else {
					uni.showLoading({
						title: '支付中...',
						mask: true
					});
					this.$emit('confirm');
					uni.setStorageSync('pay_flag', 1);
				}
			},
			complete() {
				uni.showLoading({
					title: '支付中...',
					mask: true
				});
				this.$emit('confirm');
				uni.setStorageSync('pay_flag', 1);
			},
			getPayInfo(out_trade_no) {
				this.$api.sendRequest({
					url: '/api/pay/info',
					data: {
						out_trade_no
					},
					success: res => {
						if (res.code >= 0 && res.data) {
							this.payInfo = res.data;
							this.pay();
						} else {
							this.$util.showToast({
								title: '未获取到支付信息！'
							});
							setTimeout(() => {
								this.$util.redirectTo('/pages/index/index/index', {}, 'reLaunch');
							}, 1000);
						}
					}
				});
			},
			getPayType() {
				this.$api.sendRequest({
					url: '/api/pay/type',
					data: this.payData,
					success: res => {
						if (res.code == 0) {
							if (res.data.pay_type == "") {
								this.payTypeList = [];
							} else {
								let payTypeList = [];
								this.payTypeList.forEach((val, key) => {
									if (res.data.pay_type.indexOf(val.type) != -1) {
										payTypeList.push(val);
									}
								});
								this.payTypeList = payTypeList;
								this.$forceUpdate();
							}
						}
					}
				});
			},
			// #ifdef H5
			pay() {
				var payType = this.payTypeList[this.payIndex];
				if (!payType) return;

				this.$api.sendRequest({
					url: '/api/pay/pay',
					data: {
						out_trade_no: this.payInfo.out_trade_no,
						pay_type: payType.type,
						return_url: encodeURIComponent(this.$config.h5Domain +
							'/otherpages/pay/result/result?code=' +
							this.payInfo.out_trade_no)
					},
					success: res => {
						uni.hideLoading();
						if (res.code >= 0) {
							switch (payType.type) {
								case 'YeePayBank': //转账支付
									this.$refs.transFerInfo.openPopup(this.payInfo.out_trade_no);
									this.checkPayStatus();
									break;
								case 'alipay':
									location.href = res.data.data;
									this.checkPayStatus();
									break;
								case 'wechatpay':
									if (this.$util.isWeiXin()) {
										if (res.data.type == 'aggpay') { //托管支付
											location.href = res.data.data.prePayTn;
											this.checkPayStatus();
											return;
										}
										if (uni.getSystemInfoSync().platform == 'ios') {
											var url = uni.getStorageSync('initUrl');
										} else {
											var url = location.href;
										}
										// 获取jssdk配置
										this.$api.sendRequest({
											url: '/wechat/api/wechat/jssdkconfig',
											data: {
												url: url
											},
											success: jssdkRes => {
												var wxJS = new Weixin(),
													payData = res.data.data;
												wxJS.init(jssdkRes.data);
												wxJS.pay({
														timestamp: payData.timestamp,
														nonceStr: payData.nonceStr,
														package: payData.package,
														signType: payData.signType,
														paySign: payData.paySign
													},
													res => {
														if (res.errMsg == 'chooseWXPay:ok') {
															this.$util.redirectTo(
																'/otherpages/pay/result/result', {
																	code: this.payInfo
																		.out_trade_no
																}, 'redirectTo');
														} else {
															this.$util.showToast({
																title: res.errMsg
															});
														}
													}
												);
											}
										});
									} else {
										location.href = res.data.url;
										this.checkPayStatus();
									}
									break;
							}
						} else {
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: res => {
						uni.hideLoading();
						this.$util.showToast({
							title: 'request:fail'
						});
					}
				});
			},
			checkPayStatus() {
				this.timer = setInterval(() => {
					this.$api.sendRequest({
						url: '/api/pay/status',
						data: {
							out_trade_no: this.payInfo.out_trade_no
						},
						success: res => {
							if (res.code == 0) {
								if (res.data.pay_status == 2) {
									clearInterval(this.timer);
									this.$util.redirectTo('/otherpages/pay/result/result', {
										code: this.payInfo.out_trade_no
									}, 'redirectTo');
								}
							} else {
								clearInterval(this.timer);
							}
						}
					});
				}, 1000);
			},
			// #endif
			// #ifdef MP-WEIXIN
			pay() {
				var payType = this.payTypeList[this.payIndex];
				if (!payType) return;
				if (payType.provider == 'wxpay') {
					this.$api.sendRequest({
						url: '/api/pay/pay',
						data: {
							out_trade_no: this.payInfo.out_trade_no,
							pay_type: payType.type,
							is_matched: this.isMatched
						},
						success: res => {
							uni.hideLoading();
							if (res.code >= 0) {
								var payData = res.data.data;

								if (payData.type == 'YeePayBank') {
									this.$refs.transFerInfo.openPopup(this.payInfo.out_trade_no);
									this.checkPayStatus();
									return;
								}

								if (res.data.type == 'aggpay') { //托管支付
									var version = uni.getAppBaseInfo().SDKVersion;
									if (this.$util.compareVersion(version, '2.26.2') >= 0) { //打开半屏小程序
										uni.openEmbeddedMiniProgram({
											appId: payData['appId'],
											path: payData['prePayTn'],
											extraData: payData['extraData'] ? payData['extraData'] : ''
										})
									} else {
										uni.navigateToMiniProgram({
											appId: payData['appId'],
											path: payData['prePayTn'],
											extraData: payData['extraData'] ? payData['extraData'] : ''
										})
									}

									this.checkPayStatus();
									return;
								}
								if (this.isMatched) {
									wx.requestOrderPayment({
										timeStamp: payData.timeStamp,
										nonceStr: payData.nonceStr,
										package: payData.package,
										signType: payData.signType,
										paySign: payData.paySign,
										orderInfo: payData.orderInfo,
										success: res => {
											this.$util.redirectTo(
												'/otherpages/pay/result/result', {
													code: this.payInfo.out_trade_no
												}, 'redirectTo');
										},
										fail: res => {
											this.flag = false;
											if (res.errMsg == 'requestPayment:fail cancel') {
												this.$util.showToast({
													title: '您已取消支付'
												});
											} else {
												uni.showModal({
													content: '支付失败,失败原因: ' + res.errMsg,
													showCancel: false
												});
											}
											setTimeout(() => {
												this.$util.redirectTo(
													'/otherpages/pay/result/result', {
														code: this.payInfo.out_trade_no
													}, 'redirectTo');
											}, 2000);
										}
									})
								} else {
									uni.requestPayment({
										provider: payType.provider,
										timeStamp: payData.timeStamp,
										nonceStr: payData.nonceStr,
										package: payData.package,
										signType: payData.signType,
										paySign: payData.paySign,
										success: res => {
											this.$util.redirectTo(
												'/otherpages/pay/result/result', {
													code: this.payInfo.out_trade_no
												}, 'redirectTo');
										},
										fail: res => {
											this.flag = false;
											if (res.errMsg == 'requestPayment:fail cancel') {
												this.$util.showToast({
													title: '您已取消支付'
												});
											} else {
												uni.showModal({
													content: '支付失败,失败原因: ' + res.errMsg,
													showCancel: false
												});
											}
											setTimeout(() => {
												this.$util.redirectTo(
													'/otherpages/pay/result/result', {
														code: this.payInfo.out_trade_no
													}, 'redirectTo');
											}, 1000);
										}
									});
								}

							} else {
								this.$util.showToast({
									title: res.message
								});
								setTimeout(() => {
									this.$util.redirectTo('/otherpages/pay/result/result', {
										code: this.payInfo.out_trade_no
									}, 'redirectTo');
								}, 1000);
							}
						},
						fail: res => {
							uni.hideLoading();
							this.$util.showToast({
								title: 'request:fail'
							});
						}
					});
				}
			},
			checkPayStatus() {
				this.timer = setInterval(() => {
					this.$api.sendRequest({
						url: '/api/pay/status',
						data: {
							out_trade_no: this.payInfo.out_trade_no
						},
						success: res => {
							if (res.code == 0) {
								if (res.data.pay_status == 2) {
									clearInterval(this.timer);
									this.$util.redirectTo('/otherpages/pay/result/result', {
										code: this.payInfo.out_trade_no
									}, 'redirectTo');
								}
							} else {
								clearInterval(this.timer);
							}
						}
					});
				}, 1000);
			},
			// #endif
			// #ifdef APP-PLUS || APP
			async pay() {
				var payType = this.payTypeList[this.payIndex];
				if (!payType) return;

				//获取支付配置
				let res = await this.$api.sendRequest({
					url: '/api/pay/config',
					async: false,
					data: {
						pay_type: payType.type
					}
				});
				if (res.code < 0) {
					return this.$util.showToast({
						title: '获取登录状态错误，请先登录！'
					});
				}
				let pay_config = res.data;
				console.log(pay_config)

				/* 微信app支付 唤起小程序支付 */
				if ((pay_config.channel != '' || pay_config.app_wxpay == 'wxapp') && payType.type == 'wechatpay') {
					return this.toWeappPay(pay_config.gh_id, uni.getStorageSync('token'), this.payInfo.order_id);
				}

				this.$api.sendRequest({
					url: '/api/pay/pay',
					data: {
						out_trade_no: this.payInfo.out_trade_no,
						pay_type: payType.type,
						return_url: encodeURIComponent(this.$config.h5Domain +
							'/otherpages/pay/result/result?code=' + this.payInfo.out_trade_no)
					},
					success: res => {
						console.log(res)
						uni.hideLoading();
						var payData = res.data.data;
						if (res.code >= 0) {
							switch (payType.type) {
								case 'YeePayBank': //转账支付
									this.$refs.transFerInfo.openPopup(this.payInfo.out_trade_no);
									this.checkPayStatus();
									break;
								case 'alipay':
									if (pay_config.channel != '') { //这是唤起支付宝app扫码支付
										plus.runtime.openURL(
											'alipays://platformapi/startapp?saId=10000007&qrcode=' +
											payData);
										this.checkPayStatus(); //定时检测支付状态
									} else { //这是唤起支付宝app原生支付
										let alipay_err_obj = {
											9000: '订单支付成功',
											8000: '正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态',
											4000: '订单支付失败',
											5000: '重复请求',
											6001: '用户中途取消',
											6002: '网络连接出错',
											6004: '支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态'
										};
										let alipay_success_code = 9000;
										uni.requestPayment({
											provider: 'alipay', //uniapp规定的支付宝支付类型
											orderInfo: payData,
											success: res => {
												let result = JSON.parse(res.rawdata);
												let err_code = result.resultStatus;
												let err_msg = '其他错误';
												if (err_code in alipay_err_obj) {
													err_msg = alipay_err_obj[err_code];
												}
												this.$util.showToast({
													title: err_msg
												});
												if (err_code == alipay_success_code) {
													setTimeout(() => {
														this.checkPayStatus();
													}, 1500);
												} else {
													this.$util.showToast({
														title: '支付失败,失败原因: ' + err_msg
													})
												}
											}
										});
									}
									break;
								case 'wechatpay':
									uni.requestPayment({
										provider: 'wxpay', //uniapp规定的微信支付类型
										orderInfo: JSON.stringify(payData),
										success: res => {
											if (res.errMsg == 'requestPayment:ok') {
												this.$util.showToast({
													title: '支付成功',
													success: () => {
														setTimeout(() => {
															this.$util
																.redirectTo(
																	'/otherpages/pay/result/result', {
																		code: this
																			.payInfo
																			.out_trade_no
																	},
																	'redirectTo'
																);
														}, 1500);
													}
												});
											}
										},
										fail: res => {
											console.log(res)
											// this.flag = false;
											if (res.errMsg == 'requestPayment:fail cancel') {
												this.$util.showToast({
													title: '您已取消支付'
												});
											} else {
												uni.showModal({
													content: '支付失败,失败原因: ' + res
														.errMsg,
													showCancel: false
												});
											}
											setTimeout(() => {
												this.$util.redirectTo(
													'/pages/order/list/list', {},
													'redirectTo');
											}, 2000);
										}
									});
									break;
							}
						} else {
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: res => {
						uni.hideLoading();
						this.$util.showToast({
							title: 'request:fail'
						});
					}
				});
			},
			toWeappPay(gh_id, token, order_id) { // 唤起微信小程序支付
				let _this = this;
				plus.share.getServices(
					res => {
						let sweixin = '';
						for (var i = 0; i < res.length; i++) {
							let t = res[i];
							if (t.id == 'weixin') {
								sweixin = t;
							}
						}
						if (sweixin) {
							sweixin.launchMiniProgram({
									id: gh_id, // 要跳转小程序的原始ID
									path: 'otherpages/pay/weapp_pay/weapp_pay?mid=' + token + '&oid=' +
										order_id, //  可带参数
									type: 0 // 微信小程序版本类型可取值： 0-正式版； 1-测试版； 2-体验版。 默认值为0。
								},
								res2 => { // 目标小程序点击返回App后执行的回调，在此接收微信小程序传递的参数
									// res2是微信小程序传递回来的参数 类型为string 需转化为js对象使用
									let result = JSON.parse(res2)
									console.log(result)
									// 拿到参数后执行你需要的逻辑    
									setTimeout(() => {
										_this.$util.redirectTo('/otherpages/pay/result/result', {
											code: result.code
										}, 'redirectTo');
									}, 1500);
								},
								err2 => {
									console.log(err2)
								});
							_this.checkPayStatus('order'); //定时检测支付状态
						} else {
							return _this.$util.showToast({
								title: '当前环境不支持唤起微信支付操作！'
							});
						}
					},
					err => {
						console.log(err)
					}
				)
			},
			checkPayStatus() {
				this.timer = setInterval(() => {
					this.$api.sendRequest({
						url: '/api/pay/status',
						data: {
							out_trade_no: this.payInfo.out_trade_no
						},
						success: res => {
							if (res.code == 0) {
								if (res.data.pay_status == 2) {
									clearInterval(this.timer);
									this.$util.redirectTo('/otherpages/pay/result/result', {
										code: this.payInfo.out_trade_no
									}, 'redirectTo');
								}
							} else {
								clearInterval(this.timer);
							}
						}
					});
				}, 1000);
			},
			// #endif
		},
		// #ifdef H5
		deactivated() {
			clearInterval(this.timer);
		},
		// #endif
		filters: {
			/**
			 * 金额格式化输出
			 * @param {Object} money
			 */
			moneyFormat(money) {
				return parseFloat(money).toFixed(2);
			}
		}
	};
</script>

<style lang="scss">
	.icon_img {
		width: 64rpx;
		height: 64rpx;
	}

	.popup {
		width: 75vw;
		background: #fff;
		border-top-left-radius: $border-radius;
		border-top-right-radius: $border-radius;

		.popup-header {
			display: flex;
			border-bottom: 2rpx solid $color-line;
			position: relative;
			padding: 40rpx;

			.tit {
				flex: 1;
				font-size: $font-size-toolbar;
				line-height: 1;
				text-align: center;
			}

			.iconfont {
				line-height: 1;
				position: absolute;
				right: 30rpx;
				top: 50%;
				transform: translate(0, -50%);
				color: $color-tip;
				font-size: $font-size-toolbar;
			}
		}

		.popup-body {
			height: calc(100% - 250rpx);

			&.safe-area {
				height: calc(100% - 270rpx);
			}
		}

		.popup-footer {
			height: 100rpx;

			.confirm-btn {
				height: 72rpx;
				line-height: 72rpx;
				color: #fff;
				text-align: center;
				margin: 20rpx 30rpx 0;
				border-radius: 40rpx;
			}

			&.bottom-safe-area {
				padding-bottom: constant(safe-area-inset-bottom);
				padding-bottom: env(safe-area-inset-bottom);
			}
		}
	}

	.choose-payment-popup {
		.payment-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 90rpx;
			margin: 0 30rpx;
			border-bottom: 1px solid $color-line;
			padding: 20rpx 0;

			&:nth-child(2) {
				padding-top: 0;
			}

			&:last-child {
				border-bottom: none;
			}

			.iconfont {
				font-size: 64rpx;
			}

			.iconyue {
				color: #faa218;
			}

			.iconweixin1 {
				color: #24af41;
			}

			.iconzhifubaozhifu- {
				color: #00a0e9;
			}

			.iconcheckboxblank {
				font-size: 40rpx;
				color: $color-line;
			}

			.iconyuan_checked {
				font-size: 40rpx;
			}

			.name {
				margin-left: 20rpx;
				font-size: $font-size-base;
				flex: 1;
			}

			.info-wrap {
				flex: 1;
				margin-left: 20rpx;

				.name {
					margin-left: 0;
					font-size: $font-size-base;
					flex: 1;
				}

				.money {
					color: $color-tip;
					font-size: $font-size-tag;
				}
			}

			.box {
				flex: 1;
				padding: 0 10rpx;
				line-height: inherit;
				text-align: right;

				input {
					font-size: $font-size-tag !important;
				}
			}

			&.set-pay-password {
				height: initial;

				.box {
					font-size: $font-size-tag !important;
				}
			}
		}

		.pay-money {
			text-align: center;
			padding: 20rpx 0 40rpx 0;
			background-color: #fff;
			font-weight: bold;
			margin-top: 30rpx;
			line-height: 1;

			.unit {
				margin-right: 4rpx;
				font-size: $font-size-tag;
			}

			.money {
				font-size: $font-size-toolbar;
			}
		}
	}

	.empty {
		width: 100%;
		text-align: center;
		padding: 40rpx 0;
		color: $color-sub;
		font-size: $font-size-tag;
	}
</style>